<template>
  <div class="app-container">
    <el-card>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="关键字:">
          <el-input v-model="queryForm.keyword" placeholder="请输入关键字" style="width: 128px;" prefix-icon="el-icon-search"
                    size="small"
          />
        </el-form-item>
        <el-form-item label="角色:">
          <el-select v-model="queryForm.status" size="small" style="width: 268px;" multiple placeholder="请选择">
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="fetchData(1)">查询</el-button>
        </el-form-item>
        <el-form-item style="flex-grow: 1;" />
        <el-form-item style="margin-right: 0;">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="showNewUserDialog()">新建</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        stripe
        highlight-current-row
      >
        <el-table-column align="center" label="工号" width="84">
          <template v-slot="scope">
            {{ scope.row.uid }}
          </template>
        </el-table-column>
        <el-table-column label="姓名">
          <template v-slot="scope">
            {{ scope.row.username }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="手机号" align="center" width="96">-->
        <!--          <template v-slot="scope">-->
        <!--            {{ scope.row.pageviews }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="邮箱" align="center" width="128">-->
        <!--          <template v-slot="scope">-->
        <!--            <span>{{ scope.row.author }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column class-name="status-col" label="角色" align="center">
          <template v-slot="scope">
            <el-tag>{{ scope.row.role.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="操作" align="center" width="226">
          <template v-slot="scope">
            <el-button type="primary" size="small" @click="openDialog(scope.row)">重置密码</el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-pagination
          :page-size="pageSize"
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :total="total"
          @current-change="fetchData(currentPage)"
        />
      </div>
    </el-card>
    <el-dialog
      title="警告！"
      :visible.sync="changePwdDialog"
      width="30%"
      center
    >
      <span style="width:100%;text-align: center;">{{ `${toChangePwdUserInfo.username}的密码将被重置为123456` }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changePwdDialog = false">取 消</el-button>
        <el-button type="primary" @click="resetPwd()">重 置</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="创建新用户"
      :visible.sync="addNewUserDialog"
      width="50%"
      center
    >
      <el-form ref="registerForm" :model="userForm" :rules="rules" label-width="100px">
        <el-form-item label="工号" prop="uid">
          <el-input v-model="userForm.uid" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="userForm.realname" />
        </el-form-item>
        <el-form-item label="预设密码" prop="password">
          <el-input v-model="userForm.password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色权限">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('userForm')">立即创建</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { changeOtherPwd, deleteUser, getUserList, register } from '@/api/user.js'
import { PAGE_SIZES, USER_TYPE_OPTIONS } from '@/utils/common'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('密码不小于6位'))
      } else {
        callback()
      }
    }
    return {
      options: USER_TYPE_OPTIONS,
      userOptions: USER_TYPE_OPTIONS,
      toChangePwdUserInfo: -1,
      changePwdDialog: false,
      userForm: {
        uid: '',
        username: '',
        realname: '',
        password: '123456',
        role: 1
      },
      rules: {
        uid: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      addNewUserDialog: false,
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      queryForm: {
        keyword: '',
        status: []
      },
      list: null,
      listLoading: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.fetchData(1)
  },
  methods: {
    deleteUser(item) {
      console.log(item)
      this.$confirm(`此操作将删除用户${item.realname}, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(item.uid).then(res => {
          this.$message.success('删除成功')
          this.fetchData(1)
        })
      }).catch(() => {
      })
    },
    resetPwd() {
      changeOtherPwd({ uid: this.toChangePwdUserInfo.uid, password: '123456' }).then(res => {
        this.$message.success('重置密码成功')
        setTimeout(() => {
          window.location.reload()
        }, 500)
        this.changePwdDialog = false
      }).catch(() => {
        this.$message.error('重置密码失败')
        this.changePwdDialog = false
      })
    },
    openDialog(info) {
      this.toChangePwdUserInfo = info
      this.changePwdDialog = true
    },
    showNewUserDialog() {
      this.addNewUserDialog = true
    },
    submitForm(formName) {
      this.userForm.username = this.userForm.realname
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          register(this.userForm).then(res => {
            this.$message.success('注册成功！')
            this.addNewUserDialog = false
            this.fetchData(1)
          })
        } else {
          this.$message.error('信息填写不完整，请检查')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    fetchData(page) {
      this.listLoading = true
      const params = {
        name: this.queryForm.keyword
      }
      if (this.queryForm.status.length === 1) {
        params['role'] = this.queryForm.status[0]
      } else if (this.queryForm.status.length >= 1) {
        params['role'] = `(${this.queryForm.status.join()})`
      }
      getUserList(this.pageSize, page, params).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
        this.currentPage = response.data.page
      })
    },
    viewOrder() {
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-form-inline {
  display: flex;
}
</style>
